<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\AdminModel;


class AuthAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (in_array($request->route()->getName(), $this->except)) {
            return $next($request);
        }

        $token = $request->header('X-Token');
        if (!$token) {
            return response()->json(['code' => 401,'msg' => '请先登录'], 401);
        }

        $admin = AdminModel::where('token', $token)->first();
        if (!$admin) {
            return response()->json(['code' => 401,'msg' => 'Token Invalid'], 401);
        }

        $request->merge(['admin' => $admin]);
        return $next($request);
    }

    private $except = [
        'adminLogin'
    ];
}
